import 'dart:convert';

import 'model.dart';

void main() {
  final jsonStr = r'{"name":"z2","token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MTMzLCJwaWQiOjEsImRlcHRJZCI6MTExLCJyb2xlSWQiOjIsInJvbGVLZXkiOiJtYW5hZ2UiLCJ1c2VybmFtZSI6InoyIiwicmVhbE5hbWUiOiJ6MiIsImF2YXRhciI6Imh0dHA6Ly8xMC4wLjAuMTA6MTAyMDAvYXR0YWNobWVudC8yMDI1LTA1LTE2LzQwZGQ1ZDZhNDZmNWMxMzQ0YjRlNWIzZjNmYTM4Njg0LnBuZyAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICIsImVtYWlsIjoiIiwibW9iaWxlIjoiIiwiYXBwIjoiYWRtaW4iLCJsb2dpbkF0IjoiMjAyNS0wOC0yMSAxOTozOTo0NiIsImRldmljZSI6bnVsbH0.Cd28-mLYq7WMt-viwsY43Wwl4sDwKTmCr2Z0goEvRfk","expires":604800}';

  // Parse the main response
  final authResponse = AuthResponse.fromJson(jsonDecode(jsonStr));
  print('Auth Response: $authResponse');

  // Optional: Decode JWT claims
  try {
    final jwtClaims = decodeJwtClaims(authResponse.token);
    print('JWT Claims: $jwtClaims');
  } catch (e) {
    print('Error decoding JWT: $e');
  }
}

// Helper function to decode JWT claims
JwtClaims decodeJwtClaims(String token) {
  final parts = token.split('.');
  if (parts.length != 3) {
    throw FormatException('Invalid JWT token format');
  }

  try {
    // Decode Base64Url encoded payload
    final payload = parts[1];
    final normalized = base64Url.normalize(payload);
    final decoded = utf8.decode(base64Url.decode(normalized));

    return JwtClaims.fromJson(jsonDecode(decoded));
  } catch (e) {
    throw FormatException('Failed to decode JWT claims: $e');
  }
}